package com.lt.contract.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lt.contract.bean.utils.ExcelImport;
import com.lt.contract.entity.NmCirciuitRealation;
import com.lt.contract.dao.NmCirciuitRealationDao;
import com.lt.contract.entity.NmCirciuitRealation;
import com.lt.contract.service.NmCirciuitRealationService;
import com.lt.report.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.lang.System.currentTimeMillis;

/**
 * 移动业务(NmCirciuitRealation)表服务实现类
 *
 * @author makejava
 * @since 2020-03-10 21:40:56
 */
@Service("nmCirciuitRealationService")
@Slf4j
public class NmCirciuitRealationServiceImpl implements NmCirciuitRealationService {
    @Resource
    private NmCirciuitRealationDao nmCirciuitRealationDao;

    @Autowired
    AsyncService asyncService;


    @Override
    public List<NmCirciuitRealation> queryAll(Map<String, Object> map) {
        return nmCirciuitRealationDao.queryAll(map);
    }

    @Override
    public Long queryCount(Map<String, Object> map) {
        return nmCirciuitRealationDao.queryCount(map);
    }

    @Override
    public List<NmCirciuitRealation> exportList(Map<String, Object> map) throws Exception {
//        // 写法1
        List<NmCirciuitRealation> nmCirciuitRealations = nmCirciuitRealationDao.exportList(map);
//        String fileName = "省级电路分摊收入"+System.currentTimeMillis() + ".xlsx";
////        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
////        // 如果这里想使用03 则 传入excelType参数即可
//        EasyExcel.write(fileName, NmCirciuitRealation.class).sheet("省级电路分摊收入").doWrite(nmCirciuitRealations);
//
//        // 写法2，方法二需要手动关闭流
//        fileName = System.currentTimeMillis() + ".xlsx";
//        // 这里 需要指定写用哪个class去写
//        ExcelWriter excelWriter = EasyExcel.write(fileName, NmCirciuitRealation.class).build();
//        WriteSheet writeSheet = EasyExcel.writerSheet("省级电路分摊收入").build();
//        excelWriter.write(nmCirciuitRealations, writeSheet);
//        /// 千万别忘记finish 会帮忙关闭流
//        excelWriter.finish();
        return nmCirciuitRealations;
    }


    /**
     * 新增数据
     *
     * @param nmCirciuitRealation 实例对象
     * @return 实例对象
     */
    @Override
    public NmCirciuitRealation insert(NmCirciuitRealation nmCirciuitRealation) {
        this.nmCirciuitRealationDao.insert(nmCirciuitRealation);
        return nmCirciuitRealation;
    }

    /**
     * 修改数据
     *
     * @param nmCirciuitRealation 实例对象
     * @return 实例对象
     */
    @Override
    public int update(NmCirciuitRealation nmCirciuitRealation) {
        return this.nmCirciuitRealationDao.update(nmCirciuitRealation);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.nmCirciuitRealationDao.deleteById(id) > 0;
    }

    @Override
    public String getBankListByExcel(InputStream in, String fileName, String staffId) throws Exception {
        //选择文件中的列
        String tableName = "";
        if(fileName.contains("省际电路关系维护")){
            tableName ="circuit";
        }else {
            log.error("上传文件不符合规定");
            return "请上次相关文件";
        }
        //创建Excel工作薄
        Workbook work = ExcelImport.getWorkbook(in, fileName);
        Sheet sheet = work.getSheetAt(0);
        List<String> isRecur = ExcelImport.isRecur(sheet,6);
        if(isRecur.size()>0){
            JSONObject object = new JSONObject();
            object.put("您上传的计费号以存在，请确认！",isRecur);
            return JSON.toJSONString(object);
        }
        List<List<String>> list = ExcelImport.queryRepetition(sheet,6);//第6列是计费号码
        List<Map<String,Object>> list1 = new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            list1.addAll(nmCirciuitRealationDao.queryRepetition(list.get(i)));
        }
        if(list1.size()>0){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("您上传的计费号码中已在列表中，请勿重复上传。", JSON.toJSONString(list1));
            return jsonObject.toJSONString();
        }
        List<List<NmCirciuitRealation>> lists =listNmCircuit(sheet,staffId);
        int size = lists.size();
        for (int i = 0; i <size ; i++) {
            List<NmCirciuitRealation> listI = lists.get(i);
            asyncService.executeCirciuitRealation(listI);
        }
        return "上传成功";
    }



    /**
     * 导入电路关系
     *
     * @param sheets 电路关系
     * @return
     */
    public List<List<NmCirciuitRealation>> listNmCircuit(Sheet sheets,String staffId) throws Exception {
        List<List<NmCirciuitRealation>> lists =new ArrayList<>();
        List<NmCirciuitRealation> list = new ArrayList<>();
        Cell cell = null;
        for (int j = 1; j <= sheets.getLastRowNum()+1; j++) {
            Row row = sheets.getRow(j);
            int flag =200;
            if(list.size() !=0 && list.size()%flag ==0 || j == sheets.getLastRowNum()+1){
                List<NmCirciuitRealation> copy = new ArrayList<>(list);
                lists.add(copy);
                list.clear();
            }
            if (row == null || row.getFirstCellNum() == j || row.getCell(1) == null) {
                continue;
            }else if (ExcelImport.isAllRowEmpty(row,row)){
                continue;
            }
            NmCirciuitRealation nmCirciuitRealation = new NmCirciuitRealation();
            for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                cell = row.getCell(y);
                if(cell==null || cell.toString().equals("")){
                    continue;
                }
                switch (y+1){
                    case 2:nmCirciuitRealation.setClient(ExcelImport.getCellValue(cell)); break;
                    case 3:nmCirciuitRealation.setTrellisCode(ExcelImport.getCellValue(cell)); break;
                    case 4:nmCirciuitRealation.setTrellisName(ExcelImport.getCellValue(cell)); break;
                    case 5:nmCirciuitRealation.setYzStaffId(ExcelImport.getCellValue(cell)); break;
                    case 6:nmCirciuitRealation.setAccountManager(ExcelImport.getCellValue(cell)); break;
                    case 7:nmCirciuitRealation.setSerialNumber(ExcelImport.getCellValue(cell)); break;
                }

            }
            nmCirciuitRealation.setInputStaffId(staffId);
            nmCirciuitRealation.setUpdateStaffid(staffId);
            list.add(nmCirciuitRealation);
        }
        return lists;
    }
}
